package com.wenjie.common.unifiedReturn;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


@Data
@Component
@ConfigurationProperties(prefix = "unified.response")
public class FileUtils {

    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    private List<String> excludePackages = new ArrayList<>();

    private Set<Class> excludeReturnTypes = new HashSet<>();


    public Boolean file(Method method) {

        //有ExcludeFromGracefulResponse注解修饰的，也跳过
        if (method.isAnnotationPresent(IgnorePage.class)) {
            return false;
        }

        //配置了例外包路径，则该路径下的controller都不再处理
        List<String> excludePackages = this.excludePackages;
        if (!CollectionUtils.isEmpty(excludePackages)) {
            // 获取请求所在类的的包名
            String packageName = method.getDeclaringClass().getPackage().getName();

            for (String excludePackage : excludePackages) {
                if (excludePackage.length() > packageName.length()) break;
                if (packageName.startsWith(excludePackage)) return false;
            }
        }

        //配置了例外的返回类型，则不处理
        return CollectionUtils.isEmpty(excludeReturnTypes)
                || !excludeReturnTypes.contains(method.getReturnType());
    }


}
